#!/bin/bash

# DataLink API 完整功能验证脚本
# 验证所有API端点和核心功能

echo "🚀 DataLink API 完整功能验证"
echo "=================================="

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

BASE_URL="http://127.0.0.1:9966"
TOKEN="dev-token-$(date +%s)"
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试结果记录
test_result() {
    local test_name="$1"
    local success="$2"
    local details="$3"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if [ "$success" = "true" ]; then
        echo -e "${GREEN}✅ $test_name${NC}: $details"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}❌ $test_name${NC}: $details"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
}

# API测试函数
test_api() {
    local name="$1"
    local method="$2"
    local endpoint="$3"
    local data="$4"
    
    echo -e "${BLUE}🔍 测试 $name...${NC}"
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "HTTPSTATUS:%{http_code}" \
            -H "Authorization: Bearer $TOKEN" \
            "$BASE_URL$endpoint")
    else
        response=$(curl -s -w "HTTPSTATUS:%{http_code}" \
            -X "$method" \
            -H "Authorization: Bearer $TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data" \
            "$BASE_URL$endpoint")
    fi
    
    http_code=$(echo "$response" | grep -o "HTTPSTATUS:[0-9]*" | cut -d: -f2)
    body=$(echo "$response" | sed 's/HTTPSTATUS:[0-9]*$//')
    
    if [ "$http_code" = "200" ]; then
        # 尝试解析JSON响应
        if echo "$body" | jq . >/dev/null 2>&1; then
            json_code=$(echo "$body" | jq -r '.code // "N/A"')
            message=$(echo "$body" | jq -r '.message // "N/A"')
            test_result "$name" "true" "HTTP:$http_code, JSON:$json_code"
        else
            test_result "$name" "true" "HTTP:$http_code, 响应长度:${#body}"
        fi
    else
        test_result "$name" "false" "HTTP:$http_code"
    fi
}

echo -e "${YELLOW}📋 开始API功能验证...${NC}"

# 1. 系统信息API
test_api "系统信息" "GET" "/api/system/info" ""

# 2. 用户管理API
test_api "用户列表" "POST" "/api/user/list" "{}"

# 3. 规则管理API
test_api "规则列表" "POST" "/api/rule/list" "{}"
test_api "规则创建" "POST" "/api/rule/add" '{
    "ruleName": "API测试规则",
    "remark": "通过API创建的测试规则",
    "graphJson": "{\"nodes\":[{\"id\":\"input1\",\"type\":\"input\",\"x\":100,\"y\":100}],\"edges\":[]}"
}'

# 4. 资源管理API
test_api "资源列表" "POST" "/api/resource/list" "{}"

# 5. 插件管理API
test_api "插件列表" "POST" "/api/plugin/list" "{}"

# 6. 脚本管理API
test_api "脚本列表" "POST" "/api/script/list" "{}"

# 7. 变量管理API
test_api "变量列表" "POST" "/api/variable/list" "{}"

# 8. 备份管理API
test_api "备份列表" "POST" "/api/backup/list" "{}"

# 9. 集群管理API
test_api "集群信息" "GET" "/api/cluster/info" ""

# 10. 运行时API
test_api "运行时信息" "GET" "/api/runtime/info" ""

# 11. 测试端点
test_api "测试端点" "GET" "/api/test/hello" ""

echo ""
echo "=================================="
echo -e "${BLUE}📊 API测试结果统计${NC}"
echo "=================================="
echo -e "总测试数: ${TOTAL_TESTS}"
echo -e "${GREEN}通过测试: ${PASSED_TESTS}${NC}"
echo -e "${RED}失败测试: ${FAILED_TESTS}${NC}"

if [ $TOTAL_TESTS -gt 0 ]; then
    SUCCESS_RATE=$(echo "scale=2; $PASSED_TESTS * 100 / $TOTAL_TESTS" | bc)
    echo -e "成功率: ${SUCCESS_RATE}%"
else
    echo -e "成功率: 0%"
fi

echo "=================================="

# 数据库验证
echo -e "${YELLOW}🗄️ 验证H2数据库状态...${NC}"

# 检查数据库文件
DB_FILE="datalink-web/data/datalink.mv.db"
if [ -f "$DB_FILE" ]; then
    DB_SIZE=$(ls -lh "$DB_FILE" | awk '{print $5}')
    test_result "H2数据库文件" "true" "文件大小: $DB_SIZE"
else
    test_result "H2数据库文件" "false" "数据库文件不存在"
fi

# 功能验证总结
echo ""
echo "=================================="
echo -e "${BLUE}🎯 DataLink功能验证总结${NC}"
echo "=================================="

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "${GREEN}🎉 所有功能验证通过！${NC}"
    echo -e "${GREEN}✅ LMDB → H2 迁移成功${NC}"
    echo -e "${GREEN}✅ Spring Boot 3.3.4 升级成功${NC}"
    echo -e "${GREEN}✅ Java 23 兼容性完美${NC}"
    echo -e "${GREEN}✅ 所有API端点正常工作${NC}"
    echo -e "${GREEN}✅ 数据存储功能正常${NC}"
    exit 0
else
    echo -e "${YELLOW}⚠️  部分功能需要关注${NC}"
    echo -e "通过率: ${SUCCESS_RATE}%"
    exit 1
fi
